﻿using RM.Weighing.BLL;
using RM.Weighing.Models;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace RM.Weighing.Page
{
    public partial class UIContent : UIPage
    {
        private SerialPortService serialPortService;
        private ProductBLL productBLL = new ProductBLL();
        private List<Product> products;
        private WeighingRecordBLL WeighingRecordBLL = new WeighingRecordBLL();
        private List<WeighingRecord> weighingRecords;
        private List<float> floats = new List<float>();
        private int _xh = 0;

        private float _lowWeighing;
        private float _highWeighing;

        private float weight;
        private bool total = true;

        public UIContent()
        {
            InitializeComponent();
        }


        private void SerialPortService_DataReceived(List<byte> obj)
        {

            bool a = obj.Contains(0x0D);
            int b = obj.IndexOf(0x02);
            string xss = string.Empty;
            if (a && obj.Count >= (b + 17))
            {
                try
                {
                    //List<string> strings = new List<string>();
                    byte[] zs = new byte[4] { obj[b + 5], obj[b + 6], obj[b + 7], obj[b + 8] };
                    byte[] xs = new byte[2] { obj[b + 9], obj[b + 10] };
                    int zss = Convert.ToInt32(Encoding.UTF8.GetString(zs));
                    xss = Encoding.UTF8.GetString(xs);
                    //weight = Convert.ToSingle($"{zss}.{xss}")*1000;
                    weight = Convert.ToSingle($"{zss}.{xss}");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                string sufix = string.Empty;
                if (xss.Equals("0 "))
                {
                    sufix = ".0";
                }
                if (weight == 0)
                {
                    total = true;
                }
                floats.Add(weight);
                if ((floats.Count >= 32) && total)
                {
                    floats.Sort();
                    bool v = (floats.Average() > _lowWeighing) && (floats.Average() < _highWeighing);
                    Console.WriteLine($"是否符合：{v}\r\n差值：{Math.Abs(floats[0] - floats[floats.Count - 1])}");
                    if ((Math.Abs(floats[0] - floats[floats.Count - 1]) <= 3) && v)
                    {
                        this.Invoke(new Action(() =>
                        {
                            SetData(floats.Average());
                        }));
                        total = false;
                    }
                    floats.Clear();
                }
                obj.Clear();
                this.Invoke(new Action(() =>
                {
                    uiLedLabel1.Text = weight.ToString() + sufix;
                }));
            }

        }


        private void SetData(float weighing)
        {
            int index = uiComboBox1.SelectedIndex;
            WeighingRecord weighRecord = new WeighingRecord()
            {
                ID_P = products[index].ID,
                ProductName = products[index].ProductName,
                ProductCode = products[index].ProductCode,
                RegisterDate = DateTime.Now.ToString("yyMMdd"),
                WeiGhingStandard = $"{products[index].WeightLow.Trim()}-{products[index].WeightLimit.Trim()}",
                WeiGhing = weighing.ToString(),
                SerialNumber = _xh,
            };
            if (_xh > 999)
            {
                _xh = 1;
                ShowErrorDialog("序号已达极限值，将从1从新开始");
            }
            bool v = PrintLabel.Print(weighRecord, IniSettings.Current.BQPrint);
            if (v)
            {
                WeighingRecordBLL.Add(weighRecord);
                UpdateView(products[index]);
            }
        }

        private void UIContent_Initialize(object sender, EventArgs e)
        {
            try
            {
                serialPortService = new SerialPortService(IniSettings.Current.SerialName, SerialPortBaudRateList.BaudRate_9600, SerialPortDataBitList.EightBits, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None);
                serialPortService.DataReceived += SerialPortService_DataReceived;
                if (!serialPortService.IsOpen())
                {
                    serialPortService.Open();
                }
            }
            catch (Exception ex)
            {

                ShowErrorDialog($"串口初始化错误，请确定串口号是否正确！\r\n错误代码为：{ex.Message}");
                return;
            }
        }

        private void UIContent_Finalize(object sender, EventArgs e)
        {
            if (serialPortService != null)
            {
                if (serialPortService.IsOpen())
                {
                    serialPortService.Close();
                }
            }
        }

        private void uiComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int a = uiComboBox1.SelectedIndex;
            Product product = products[a];
            uiTextBox1.Text = product.ProductCode;
            uiTextBox2.Text = product.WeightLimit;
            uiTextBox3.Text = product.WeightLow;
            _lowWeighing = Convert.ToSingle(product.WeightLow);
            _highWeighing = Convert.ToSingle(product.WeightLimit);
            UpdateView(product);
        }

        private void UpdateView(Product product)
        {
            //创建存储参数的数组
            SqlParameter[] sqlParameters = new[]
            {
                //将产品ID存入
                new SqlParameter("@iD_P",SqlDbType.Int,4){Value = product.ID},
                //将产品代码存入
                new SqlParameter("@productCode",SqlDbType.NVarChar,100){Value = product.ProductCode ?? string.Empty},
                //将采集日期存入
                new SqlParameter("@registerDate",SqlDbType.NVarChar,100){Value = DateTime.Now.ToString("yyMMdd")},
            };

            weighingRecords = WeighingRecordBLL.GetModelList("ID_P = @iD_P AND ProductCode = @productCode AND RegisterDate = @registerDate", sqlParameters);
            if (weighingRecords.Count == 0)
            {
                _xh = 1;
            }
            else
            {
                _xh = weighingRecords.Count + 1;
                for (int i = 0; i < weighingRecords.Count; i++)
                {
                    weighingRecords[i].XH = i + 1;
                    weighingRecords[i].ProductName = product.ProductName;
                }
            }
            uiDataGridView1.DataSource = weighingRecords;
        }

        private void UIContent_Load(object sender, EventArgs e)
        {
            products = productBLL.GetAllModel();
            uiComboBox1.DataSource = products;
            uiComboBox1.SelectedIndex = 0;
            uiComboBox1.DisplayMember = "ProductName";
        }
    }
}
